<?php
/**
 * Created by PhpStorm.
 * User: BlueIdeaLirui
 * Date: 2020/02/28
 * Time: 14:01
 */

namespace console\controllers\platform;

use business\company\models\SupplierBasicModel;
use common\utils\DateTimeUtils;
use yii\console\Controller;

/**
 * 供应商数据更新控制器
 * 针对于未来有供应商数据需要调度更新
 * Class UpdateSupplierDataController
 * @package console\controllers\platform
 */
class UpdateSupplierDataController extends Controller
{
    /**
     * 大数据更新同步注册资金到平台供应商（默认2017年以前的供应商数据）
     * php yii platform/update-supplier-data/update-reg-capital
     */
    public function actionUpdateRegCapital($time = '2017-12-31')
    {
        try {
            echo '开始时间' . microtime() . PHP_EOL;
            $time = !empty($time) ? $time : DateTimeUtils::date();
            $supplierIds = $this->getSupplierIdsList($time);
            if (empty($supplierIds)) {
                echo '没有找到供应商';
                return;
            }

            $offset = 100;
            $supplierCount = count($supplierIds);
            $loopCount = intval($supplierCount / $offset) + 1;
            echo '总数: ' . $loopCount . PHP_EOL;
            echo '正在进行: ' . PHP_EOL;
            for ($i = 0; $i < $loopCount; $i++) {
                echo $i . "\n";
                for ($j = $i * $offset; $j < ($i + 1) * $offset && $j < $supplierCount; $j++) {
                    $supplierId = $supplierIds[$j];
                    try {
                        $supplier = SupplierBasicModel::findOne(['supplier_id' => $supplierId]);
                        if (!empty($supplier)) {
                            $companyName = $supplier->companyName;
                            $bigSupplier = $this->getBigdataSupplierInfoByCompanyName(
                                $companyName, 'id, name, num_capi');
                            if (!empty($bigSupplier)) {
                                $numCapi = intval($bigSupplier['num_capi']);
                                if ($numCapi > 0) {
                                    echo $bigSupplier['name'] . '|' . $numCapi . PHP_EOL;
                                    $rs = $this->updateSupplier(['reg_capital_cny' => $numCapi], ['supplier_id' => $supplierId]);
                                    if (!$rs) {
                                        \Yii::error('update supplier failed! supplier_id:' . $supplierId);
                                    }
                                    echo 'success supplier_id is ' . $supplierId . PHP_EOL;
                                }
                            }
                        }
                    } catch (\Exception $e) {
                        echo 'update failed! supplier_id:' . $supplierId . PHP_EOL;
                    }
                }
            }
            echo '结束时间' . microtime()  . PHP_EOL;
        } catch (\Exception $ex){
            \Yii::error($ex->getMessage());
            echo '数据更新出错，错误信息：'.$ex->getMessage();
        }
    }

    /**
     * 返回供应商id
     * @param string $time
     * @return array
     */
    protected function getSupplierIdsList($time = '')
    {
        $query = SupplierBasicModel::find()
            ->select('supplier_id');
        $time && $query->andWhere('created_time <= :time', [':time' => $time]);
        $data = $query->column();
        return $data;
    }

    /**
     * 返回大数据供应商数据
     * @param string $companyName
     * @param string $col
     * @return mixed
     * @throws \yii\base\InvalidConfigException
     */
    protected function getBigdataSupplierInfoByCompanyName($companyName = '', $col = '*')
    {
        $sql = <<<sql
            SELECT
                $col
            FROM
                mycommunity_contractor_bigdata.yl_s_supplier
            where `name` = :company_name
sql;
        return \Yii::$app->get('dbSupplierBigdata')
            ->createCommand($sql)
            ->bindValue(':company_name', $companyName)
            ->queryOne();
    }

    /**
     * 更新平台供应商
     * @param $columns
     * @param string $condition
     * @return int
     * @throws \yii\db\Exception
     */
    protected function updateSupplier($columns, $condition = '')
    {
        return SupplierBasicModel::getDb()
            ->createCommand()
            ->update(SupplierBasicModel::tableName(), $columns, $condition)
            ->execute();
    }
}
